package com.le.tester.book.concurrentchallenge.concurrenttest12;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * createTime：2025-05-11 10:10
 * description：测试线程工厂
 */
public class TestingThreadFactory implements ThreadFactory {

    public final AtomicInteger numCreated = new AtomicInteger();
    private final ThreadFactory factory = Executors.defaultThreadFactory();

    @Override
    public Thread newThread(Runnable r) {
        numCreated.incrementAndGet();
        return factory.newThread(r);
    }

    public void testPoolExpansion() {
        int MAX_SIZE = 10;
        ExecutorService exec = Executors.newFixedThreadPool(MAX_SIZE);

        for (int i = 0; i < 10 * MAX_SIZE; i++) {
            exec.execute(() -> {
                try {
                    Thread.sleep(Long.MAX_VALUE);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            });
        }
//        for (int i = 0, i<20 && threadFactory.numCreated.get() < MAX_SIZE，i++){
//            Thread.sleep(10);
//        }
//        assert threadFactory.numCreated.get() == MAX_SIZE;
        exec.shutdown();
    }
}
